package cn.tedu.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jt.common.pojo.Product;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.management.Query;
import java.util.ArrayList;
import java.util.List;

@Service
public class SearchService {
    @Autowired
    private TransportClient client;
    private static final ObjectMapper mapper = new ObjectMapper();
    public List<Product> search(String text, Integer page, Integer rows) {
        try {
            MatchQueryBuilder query = QueryBuilders.matchQuery("productName",text);
            SearchRequestBuilder request = client.prepareSearch("easymall");
            request.setQuery(query).setFrom((page-1)*rows).setSize(rows);
            SearchResponse response = request.get();
            SearchHit[] hits = response.getHits().getHits();
            List<Product> pList = new ArrayList<>();
            for (SearchHit hit: hits
                 ) {
                String json = hit.getSourceAsString();
                Product product = mapper.readValue(json,Product.class);
                pList.add(product);
            }
            return pList;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
        //构造搜索条件query
        //调用client方法传递query from-start size=rows
    }
}
